<template>
	<view class="u-code-wrap">
		<!-- 此组件功能由js完成，无需写html逻辑 -->
	</view>
</template>

<script>
	
	export default {
		name: "u-verification-code",
		props: {
			
			seconds: {
				type: [String, Number],
				default: 60
			},
			
			startText: {
				type: String,
				default: '获取验证码'
			},
			
			changeText: {
				type: String,
				default: 'X秒重新获取'
			},
			
			endText: {
				type: String,
				default: '重新获取'
			},
			
			keepRunning: {
				type: Boolean,
				default: false
			},
			
			uniqueKey: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				secNum: this.seconds,
				timer: null,
				canGetCode: true, 
			}
		},
		mounted() {
			this.checkKeepRunning();
		},
		watch: {
			seconds: {
				immediate: true,
				handler(n) {
					this.secNum = n;
				}
			}
		},
		methods: {
			checkKeepRunning() {
				
				let lastTimestamp = Number(uni.getStorageSync(this.uniqueKey + '_$uCountDownTimestamp'));
				if(!lastTimestamp) return this.changeEvent(this.startText);
				
				let nowTimestamp = Math.floor((+ new Date()) / 1000);
				
				if(this.keepRunning && lastTimestamp && lastTimestamp > nowTimestamp) {
					
					this.secNum = lastTimestamp - nowTimestamp;
					
					uni.removeStorageSync(this.uniqueKey + '_$uCountDownTimestamp');
					
					this.start();
				} else {
					
					this.changeEvent(this.startText);
				}
			},
			
			start() {
				
				if(this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				this.$emit('start');
				this.canGetCode = false;
				
				this.changeEvent(this.changeText.replace(/x|X/, this.secNum));
				this.setTimeToStorage();
				this.timer = setInterval(() => {
					if (--this.secNum) {
						
						this.changeEvent(this.changeText.replace(/x|X/, this.secNum));
					} else {
						clearInterval(this.timer);
						this.timer = null;
						this.changeEvent(this.endText);
						this.secNum = this.seconds;
						this.$emit('end');
						this.canGetCode = true;
					}
				}, 1000);
			},
			
			reset() {
				this.canGetCode = true;
				clearInterval(this.timer);
				this.secNum = this.seconds;
				this.changeEvent(this.endText);
			},
			changeEvent(text) {
				this.$emit('change', text);
			},
			
			setTimeToStorage() {
				if(!this.keepRunning || !this.timer) return;
				
				
				if(this.secNum > 0 && this.secNum <= this.seconds) {
					
					let nowTimestamp = Math.floor((+ new Date()) / 1000);
					
					uni.setStorage({
						key: this.uniqueKey + '_$uCountDownTimestamp',
						data: nowTimestamp + Number(this.secNum)
					})
				}
			}
		},
		
		beforeDestroy() {
			this.setTimeToStorage();
			clearTimeout(this.timer);
			this.timer = null;
		}
	}
</script>

<style lang="scss" scoped>
	@import "../../libs/css/style.components.scss";
	
	.u-code-wrap {
		width: 0;
		height: 0;
		position: fixed;
		z-index: -1;
	}
</style>
